﻿using B.S.BaseData.ErrorCode;
using B.S.BaseData.Manage.Api.With.Apliaction.Command.InventoryCommand;
using B.S.Passport.ErrorCode;
using DAL;
using MediatR;
using System;
using System.Data;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.BaseData.Manage.Api.With.Apliaction.CommandHandler.StoreCommand
{
    /// <summary>
    /// 入库修改
    /// </summary>
    public class StoreUpdateCommandHandler : IRequestHandler<StoreUpdateCommand, ApiReqult<object>>
    {
        private readonly DBHelper _dbHelper;
        private const int BatchSize = 100; // 每批处理的数据数量

        public StoreUpdateCommandHandler(DBHelper dbHelper)
        {
            _dbHelper = dbHelper;
        }

        /// <summary>
        /// 入库修改
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回任务</returns>
        public async Task<ApiReqult<object>> Handle(StoreUpdateCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiReqult<object>();
            int totalRowsAffected = 0;

            // 前置检查：Id列表为null时直接返回错误
            if (request.Id == null)
            {
                result.Code = ApiEnum.操作失败;
                result.Msg = "更新操作需要提供有效的Id列表，Id参数不能为null";
                return result;
            }

            if (request.Id.Count == 0)
            {
                result.Code = ApiEnum.操作失败;
                result.Msg = "更新操作需要提供有效的Id列表，Id列表不能为空";
                return result;
            }

            for (int i = 0; i < request.Id.Count; i += BatchSize)
            {
                int endIndex = Math.Min(i + BatchSize, request.Id.Count);
                string batchSql = BuildBatchUpdateSql(request, i, endIndex);

                try
                {
                    int rowsAffected = _dbHelper.NonQuery(batchSql);
                    totalRowsAffected += rowsAffected;
                }
                catch (System.Exception ex)
                {
                    result.Code = ApiEnum.修改失败;
                    result.Msg = $"入库信息更新失败：{ex.Message}";
                    return result;
                }
            }

            result.Code = totalRowsAffected > 0 ? ApiEnum.修改成功 : ApiEnum.修改失败;
            result.Msg = totalRowsAffected > 0 ? "入库信息更新成功" : "未找到要更新的入库记录";

            return result;
        }

        private string BuildBatchUpdateSql(StoreUpdateCommand request, int startIndex, int endIndex)
        {
            string sqlTemplate = @"
            UPDATE ManagementModels
            SET Pid = {0},
                InboundNum = '{1}',
                AssociatedNum = '{2}',
                Batch = '{3}',
                Specifications = '{4}',
                Quantity = '{5}',
                Price = '{6}',
                Binlocation = '{7}',
                Storage = {8},
                Supplier = '{9}',
                SupplierID = '{10}',
                SupplierName = '{11}',
                SupplierPeople = '{12}',
                SupplierPhone = '{13}',
                Creator = '{14}',
                Reviewer = '{15}',
                OutAuditTime = {16},
                OutAuditstatus = {17},
                OutCreationTime = {18},
                Rember = '{19}',
                IsDelete = {20},
                ProName = '{21}',
                ProId = '{22}',
                Unitprice = '{23}',
                UNumber = '{24}'
            WHERE Id = {25};";

            string EscapeSingleQuotes(string input)
            {
                return input?.Replace("'", "''") ?? string.Empty;
            }

            string GetDateTimeValue(DateTime? dateTime)
            {
                return dateTime.HasValue ? $"'{dateTime.Value.ToString("yyyy-MM-dd HH:mm:ss")}'" : "NULL";
            }

            string GetEnumValue(ApiStatus? status)
            {
                return status.HasValue ? ((int)status.Value).ToString() : "NULL";
            }

            string batchSql = "";
            for (int i = startIndex; i < endIndex; i++)
            {
                var id = request.Id[i];
                if (id == null) // 处理单个Id为null的情况（根据业务需求决定处理方式）
                {
                    // 这里可以选择记录日志、跳过无效Id或抛出异常，当前示例选择跳过
                    continue;
                }

                batchSql += string.Format(sqlTemplate,
                    request.Pid?[i] ?? 0,
                    EscapeSingleQuotes(request.InboundNum?[i]),
                    EscapeSingleQuotes(request.AssociatedNum?[i]),
                    EscapeSingleQuotes(request.batch?[i]),
                    EscapeSingleQuotes(request.Specifications?[i]),
                    EscapeSingleQuotes(request.Quantity?[i]),
                    EscapeSingleQuotes(request.Price?[i]),
                    EscapeSingleQuotes(request.Binlocation?[i]),
                    (int?)(request.Storage?[i]) ?? 0,
                    EscapeSingleQuotes(request.Supplier?[i]),
                    EscapeSingleQuotes(request.SupplierID?[i]),
                    EscapeSingleQuotes(request.SupplierName?[i]),
                    EscapeSingleQuotes(request.SupplierPeople?[i]),
                    EscapeSingleQuotes(request.SupplierPhone?[i]),
                    EscapeSingleQuotes(request.Creator?[i]),
                    EscapeSingleQuotes(request.Reviewer?[i]),
                    GetDateTimeValue(request.OutAuditTime?[i]),
                    GetEnumValue(request.OutAuditstatus?[i]),
                    GetDateTimeValue(request.OutCreationTime?[i]),
                    EscapeSingleQuotes(request.Rember?[i]),
                    request.IsDelete?[i] ?? 0,
                    EscapeSingleQuotes(request.ProName?[i]),
                    EscapeSingleQuotes(request.ProId?[i]),
                    EscapeSingleQuotes(request.Unitprice?[i]),
                    EscapeSingleQuotes(request.UNumber?[i]),
                    request.Id[i]);
            }

            return batchSql;
        }
    }
}